package com.xinjian.jianba.service.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.DocWriteResponse;
import org.elasticsearch.action.DocWriteResponse.Result;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.xinjian.jianba.dao.dwmid.UserInfoDao;
import com.xinjian.jianba.dto.es.ChooseDto;
import com.xinjian.jianba.dto.es.EsServiceResult;
import com.xinjian.jianba.dto.es.FindDocDto;
import com.xinjian.jianba.enity.UserInfoEnity;
import com.xinjian.jianba.exception.BusinessException;
import com.xinjian.jianba.exception.ResponseCode;
import com.xinjian.jianba.service.YueJianService;
import com.xinjian.jianba.utils.DateUtil;
import com.xinjian.jianba.utils.EsUtil;
import com.xinjian.jianba.utils.TimeUtil;
@Service
public class YueJianServiceImpl implements YueJianService{
	@Autowired
	private EsServiceImpl esServiceImpl;
	@Autowired
	private UserInfoDao userInfoDao;
	@Override
	public EsServiceResult  indexDocumentUserId(ChooseDto chooseDto) throws IOException {
		XContentBuilder builder = XContentFactory.jsonBuilder();
		String date=TimeUtil.formatToString(new Date());
        builder.startObject();
        {
            builder.field(EsUtil.userId, chooseDto.getUserId());
            if(chooseDto.getTheme()!=null||!chooseDto.getTheme().equals("")){
            	builder.field(EsUtil.theme, chooseDto.getTheme());
            }
            builder.field(EsUtil.nickName, chooseDto.getNickName());
            builder.field(EsUtil.sex, chooseDto.getSex());
            builder.field(EsUtil.createTime,date);
            builder.field(EsUtil.lastUpdateTime, date);
            builder.array(EsUtil.location, new Float[]{chooseDto.getLngfloat(),chooseDto.getLatfloat()});
            builder.field(EsUtil.isOnline, 1);
            builder.field(EsUtil.onLineTime,date);
        }
       builder.endObject();
       EsServiceResult response= esServiceImpl.indexDocumentUserId(EsUtil.oneKeyIndex, EsUtil.oneKeyType, builder,String.valueOf(chooseDto.getUserId()));
       EsServiceResult result=null;
       if(response.getStatus()==EsServiceResult.ResultStatus.CONFLICT.getValue()){
    	   result = updateDocumentsUserId(chooseDto);
       }else{
    	   return response;
       }
      return result;
	}
	@Override
	public EsServiceResult updateDocumentsUserId(ChooseDto chooseDto) throws IOException {
		   XContentBuilder upbuilder=null;
		   upbuilder = XContentFactory.jsonBuilder();
		   String update=TimeUtil.formatToString(new Date());
		   upbuilder.startObject();
         {
      	   upbuilder.field(EsUtil.userId, chooseDto.getUserId());
	       if(chooseDto.getTheme()!=null||!chooseDto.getTheme().equals("")){
	      		upbuilder.field(EsUtil.theme, chooseDto.getTheme());
	       }
      	   upbuilder.field(EsUtil.nickName, chooseDto.getNickName());
      	   upbuilder.field(EsUtil.sex, chooseDto.getSex());
      	   upbuilder.field(EsUtil.lastUpdateTime, update);
      	   upbuilder.array(EsUtil.location, new Float[]{chooseDto.getLngfloat(),chooseDto.getLatfloat()});
      	   upbuilder.field(EsUtil.isOnline, 1);
      	   upbuilder.field(EsUtil.onLineTime,update);
         }
         upbuilder.endObject();
         EsServiceResult updateResponse= esServiceImpl.updateDocumentsUserId(EsUtil.oneKeyIndex, EsUtil.oneKeyType, upbuilder, String.valueOf(chooseDto.getUserId()));
         EsServiceResult result=null;
         if(updateResponse.getStatus()==EsServiceResult.ResultStatus.NOT_FOUND.getValue()){
        	 result=indexDocumentUserId(chooseDto);
         }else{
	    	   return updateResponse;
	      }
         return result;
	}
	@Override
	public EsServiceResult findByUid(String userId) throws IOException {
		EsServiceResult esServiceResult=esServiceImpl.findByDocId(EsUtil.oneKeyIndex, EsUtil.oneKeyType,userId);
		return esServiceResult;
	}
	@Override
	public EsServiceResult findPersons(FindDocDto findDocDto) throws IOException {
		EsServiceResult result=esServiceImpl.findPersons(EsUtil.oneKeyIndex, EsUtil.oneKeyType,findDocDto);
		//上传自己的位置
		ChooseDto chooseDto=new ChooseDto();
		chooseDto.setLatfloat(findDocDto.getLatfloat());
		chooseDto.setLngfloat(findDocDto.getLngfloat());
		chooseDto.setNickName(findDocDto.getNickName());
		chooseDto.setSex(findDocDto.getSex());
		chooseDto.setTheme(findDocDto.getTheme());
		chooseDto.setUserId(findDocDto.getUserId());
		EsServiceResult EsResult=indexDocumentUserId(chooseDto);
		//如果根据主题匹配不到人,则不根据主题匹配
		if(CollectionUtils.isEmpty(result.getList())){
			findDocDto.setTheme("");
			result=esServiceImpl.findPersons(EsUtil.oneKeyIndex, EsUtil.oneKeyType,findDocDto);
		}
		if(EsResult.getStatus()==EsServiceResult.ResultStatus.ERROR.getValue()){
			throw new BusinessException(ResponseCode.ERROR, "查询失败请稍后再试");
		}
		//整理返回数据
		List<Map<String,Object>> list=result.getList();
		List<Map<String,Object>> reList=new ArrayList<Map<String,Object>>();
		if(result.getStatus()==EsServiceResult.ResultStatus.SUCCESS.getValue()){
			for(Map<String,Object> map:list){
				Map<String,Object> remap=resultContent(map);
				if(remap!=null){
					reList.add(remap);
				}
			}
			result.setList(reList);
		}
		
		return result;
	}

	public Map<String,Object> resultContent(Map<String,Object> map){
		Map<String,Object> reMap=new HashMap<String,Object>();
		long userId=Long.parseLong(map.get(EsUtil.userId).toString());
		UserInfoEnity userInfo=userInfoDao.findById(userId);
		if(userInfo==null||userInfo.getIs_register()==0){
			return null;
		}
		if (userInfo.getBirthday() == null) {
			Date bir = DateUtil.parse("1991-01-01");
			reMap.put("age", DateUtil.getAge(bir));
		} else {
			
			reMap.put("age", DateUtil.getAge(userInfo.getBirthday()));
		}

		if (userInfo.getBirthday() == null) {
			Date bir = DateUtil.parse("1991-01-01");
			reMap.put("constellation", DateUtil.getConstellation(bir));
		} else {
			reMap.put("constellation", DateUtil.getConstellation(userInfo.getBirthday()));
		}
		reMap.put("id", userId);
		if (StringUtils.isBlank(userInfo.getNickname())) {
			if (userInfo.getSex() != null && userInfo.getSex().intValue() == 0) {
				reMap.put("nickname", "帅哥");
			} else {
				reMap.put("nickname", "美女");
			}
		} else {
			reMap.put("nickname", userInfo.getNickname());
		}
		reMap.put("sex", userInfo.getSex());
		reMap.put("userLogo", userInfo.getUserLogo());
		reMap.put("distance", map.get("calDistance"));
		reMap.put(EsUtil.isOnline, map.get(EsUtil.isOnline));
		reMap.put(EsUtil.theme, map.get(EsUtil.theme));
		return reMap;
	}
	@Override
	public EsServiceResult deleteDocByDocId(String docId) {
		EsServiceResult esServiceResult=esServiceImpl.deleteDocByDocId(EsUtil.oneKeyIndex, EsUtil.oneKeyType, docId);
		return esServiceResult;
	}
}
